package info.touret.winecellar.bottle.client;

import info.touret.winecellar.bottle.shared.BottleProxy;
import info.touret.winecellar.bottle.shared.TastingProxy;
import info.touret.winecellar.userinfo.client.UserInfoRequest;
import info.touret.winecellar.userinfo.client.UserInfoRequestFactory;

import java.util.Date;
import java.util.Set;

import com.google.gwt.activity.shared.Activity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.web.bindery.requestfactory.shared.EntityProxyChange;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.ServerFailure;
import com.google.web.bindery.requestfactory.shared.Violation;

/**
 * Widget permettant l affichage d une dialogbox affichant un formulaire de saisie de degustation
 *
 * @author touret-a
 */
public class TastingUI extends DialogBox implements
        EntityProxyChange.Handler<TastingProxy>, Activity {

    private static TastingUIUiBinder uiBinder = GWT.create(TastingUIUiBinder.class);

    interface TastingUIUiBinder extends UiBinder<Widget, TastingUI> {
    }

    /**
     * Constructeur vide ( a ne pas utiliser ...)
     */
    public TastingUI() {
        setWidget(uiBinder.createAndBindUi(this));
        tastingrequestfactory = GWT
        .create(TastingRequestFactory.class);
        tastingrequestfactory.initialize(new SimpleEventBus());
        setAnimationEnabled(true);
        setGlassEnabled(true);
        makeNotes();
        makeQuantities();
    }

    public TastingUI(BottleProxy _currentBottle){
    	this();
    	setCurrentBottle(_currentBottle);
    }
    
    private TastingRequestFactory tastingrequestfactory;

    /**
     * @param factory factory des objets tasting ( l initialisation doit etre cree auparavant )
     * @param bottle  bouteille degustee
     */
    public TastingUI(TastingRequestFactory factory) {
        this();
        tastingrequestfactory = factory;
        setAnimationEnabled(true);
        setGlassEnabled(true);
        makeNotes();
        makeQuantities();
    }

    private BottleProxy currentBottle;

    /**
     * @return la bouteille a deguster
     */
    public BottleProxy getCurrentBottle() {
        return currentBottle;
    }

    /**
     * @param currentBottle la bouteille a deguster
     */
    public void setCurrentBottle(BottleProxy currentBottle) {
        this.currentBottle = currentBottle;
    }

    @Override
    public String mayStop() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCancel() {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStop() {
        // TODO Auto-generated method stub
    }

    @Override
    public void start(AcceptsOneWidget panel, EventBus eventBus) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProxyChange(EntityProxyChange<TastingProxy> event) {
    }

    private void closeDialog() {
        clearForm();
        hide();
    }

    @UiHandler("rollbackbutton")
    void onRollbackbuttonClick(ClickEvent event) {
        closeDialog();
    }

    @UiField
    ListBox note = new ListBox(false);
    @UiField
    ListBox quantity = new ListBox(false);
    @UiField(provided = true)
    DateBox tasted = new DateBox();

    /**
     * Cree les notes necessaires a la degustation
     */
    private void makeNotes() {
        NotesFactory.getFactory().makeNotes(note);
    }

    /**
     * cree les quantites. Intialise le max a la quantite presente en cave
     */
    private void makeQuantities() {
        int max = 50;
        if (getCurrentBottle() != null) {
            max = getCurrentBottle().getQuantity().intValue();
        }
        System.err.println("max=" + max);
        for (int i = 0; i <= max; i++) {
            quantity.addItem(String.valueOf(i), String.valueOf(i));
        }
    }

    /**
     * Validation du formulaire
     *
     * @param event
     */
    @UiHandler("submitbutton")
    void onSubmitbuttonClick(ClickEvent event) {
        TastingRequest request = tastingrequestfactory.tastingRequest();
        TastingProxy proxy = request.create(TastingProxy.class);
        UserInfoRequestFactory userinfofactory = GWT.create(UserInfoRequestFactory.class);
        UserInfoRequest userinforequest = userinfofactory.userinfoRequest();
        proxy.setBottleID(getCurrentBottle().getId());
        proxy.setNote(Integer.parseInt(note.getValue(note.getSelectedIndex())));
        final Integer q = Integer.parseInt(quantity.getValue(quantity.getSelectedIndex()));
        proxy.setQuantity(q);
        proxy.setTasted(tasted.getValue());
        request.addTasting().using(proxy).fire(new Receiver<Void>() {

            @Override
            public void onSuccess(Void response) {
                Window.alert("Insertion OK");

            }

            @Override
            public void onViolation(Set<Violation> errors) {

                super.onViolation(errors);
                System.err.println("errors.toString()=" + errors.toString());
            }

            @Override
            public void onFailure(ServerFailure error) {
                super.onFailure(error);
            }
        });
        closeDialog();
    }

    /**
     * Vide le formulaire
     */
    private void clearForm() {
        note.setSelectedIndex(0);
        quantity.setSelectedIndex(0);
        tasted.setValue(new Date());
        setVisible(false);
    }
}
